<script lang="tsx">
import { Skeleton } from '~/components/skeleton';
import SelectToken from './SelectToken.vue';

type TCurrencyBalance = Api.GetData<typeof apis.apiFundWithdrawReady>['currency_balance_list'];

/** 币种选择 */
function useCurrencySelect(currencyList: Ref<TCurrencyBalance | undefined>) {
  const currencyName = ref('');
  const chainName = ref('');
  const currency = computed(() => {
    const targetCurrency = currencyList.value?.find(item => item.currency === currencyName.value);
    if (!targetCurrency)
      return;

    return {
      ...targetCurrency,
      token: targetCurrency.tokens?.find(item => item.chain === chainName.value),
    };
  });

  watch(currencyList, (val) => {
    if (val) {
      currencyName.value = val[0].currency;
      chainName.value = val[0].tokens?.[0].chain ?? '';
    }
  }, { immediate: true });

  return { currencyName, chainName, currency };
}

/** 充值地址 */
function useWalletAddress(currency: Ref<string>, chain: Ref<string>) {
  const walletAddressQry = useQuery({
    enabled: () => !!(currency.value && chain.value),
    queryKey: [apis.apiFundDepositGetAddress.id, currency, chain],
    queryFn: () => apis.apiFundDepositGetAddress({ requestBody: { currency: currency.value, chain: chain.value } }),
    gcTime: 0,
  });
  const walletAddress = computed(() => walletAddressQry.data.value?.wallet_address ?? '');

  return { walletAddressQry, walletAddress };
}

export function LoadingComponent() {
  return (
    <Skeleton class="grid gap-3">
      <div class="grid grid-cols-2 gap-3">
        <Skeleton type="rect" width="auto" />
        <Skeleton type="rect" width="auto" />
      </div>
      <div class="grid row-span-2 grid-cols-[1fr_auto] content-start items-start gap-3">
        <Skeleton type="text" length={80} />
        <Skeleton type="rect" class="row-span-2" size={140} />
        <Skeleton type="rect" width="auto" />
      </div>
      <Skeleton type="rect" />
    </Skeleton>
  );
}
</script>

<script setup lang="tsx">
const depositReadyQry = useQuery({
  queryKey: [apis.apiFundDepositReady.id],
  queryFn: () => apis.apiFundDepositReady(undefined),
  gcTime: 0,
});

const currencyList = computed(() => depositReadyQry.data.value?.currency_balance_list);
const { currencyName, chainName, currency } = useCurrencySelect(currencyList);
const { walletAddressQry, walletAddress } = useWalletAddress(currencyName, chainName);
const openWalletAddress = useBoolean();

onActivated(() => {
  depositReadyQry.refetch();
});

await depositReadyQry.suspense();
await walletAddressQry.suspense();
</script>

<template>
  <div class="grid gap-3 text-sm">
    <SelectToken
      v-model:currency="currencyName" v-model:chain="chainName"
      :list="depositReadyQry.data.value?.currency_balance_list"
    />

    <!-- 钱包地址 -->
    <template v-if="!walletAddressQry.isError.value">
      <div>
        <I18nT keypath="mxuQiC5Sz2t99dgmRjuJe" tag="div" class="mb-2">
          <template #name>
            {{ currency?.currency }}
          </template>
        </I18nT>
        <div class="grid grid-cols-[1fr_auto] gap-3">
          <I18nT keypath="dE0Irc3DXrTauBywLJrO" tag="div" class="text-sys-text-body">
            <template #network>
              {{ currency?.token?.network }}
            </template>
            <template #chain>
              ({{ currency?.token?.chain }})
            </template>
            <template #currency>
              {{ currency?.currency }}
            </template>
          </I18nT>
          <div class="row-span-2 size-20 rounded-2 bg-white p2 op-90" u:tablet="size-35">
            <AQrcode
              :value="walletAddress" :size="400" color="#000" bgColor="#FFF"
              :status="walletAddressQry.isPending.value ? 'loading' : 'active'"
              @click="walletAddressQry.isSuccess.value && $bp.ltTablet && openWalletAddress.setTrue()"
            />
          </div>
          <div v-if="walletAddress" class="flex-between rounded-2 bg-sys-layer-d px-4 py-3" u:lt-tablet="col-span-2">
            <span class="w-[90%] break-all">{{ walletAddress }}</span>
            <TCopy :source="walletAddress" :nthParent="1" />
          </div>
        </div>
      </div>

      <div class="rounded-2 bg-sys-layer-d px-4 py-3 leading-normal">
        <i class="i-local:warning mr-2 text-4" />
        <span>
          {{ $t('bi4qKzRqUa9PbYlaBa9nz') }}
          {{ currency?.token?.min_deposit_amount ?? 0 }} {{ currency?.token?.currency }}.
        </span>
      </div>

      <div class="text-sys-text-body leading-normal">
        {{ depositReadyQry.data.value?.tips }}
      </div>
    </template>
    <div v-else class="h-60 flex-center text-center text-base text-red-5">
      This token is temporarily not supported.
    </div>

    <AModal
      v-model:open="openWalletAddress.is" title="Deposit Address"
      wrapClassName="ant-cover__Modal-drawer"
      centered :footer="null"
    >
      <div class="mx-auto my-10 size-60 rounded-2 bg-white p-3">
        <AQrcode :value="walletAddress" :size="400" color="#000" bgColor="#FFF" />
      </div>
    </AModal>
  </div>
</template>
